﻿using System;
using System.Collections.Generic;
using System.Linq;

using Cirrious.MvvmCross.Plugins.Sqlite;

namespace Bulb.Core.Services.DataStore
{
    public class BulbItemRepository : IRepository<BulbItem>
    {
        private readonly ISQLiteConnection _connection;

        public BulbItemRepository(ISQLiteConnectionFactory factory)
        {
            _connection = factory.Create("bulbitemcollect.sql");
            _connection.CreateTable<BulbItem>();

            if (Count() == 0)
            {
                Add(new BulbItem
                    {
                        Name = "Example Light",
                        Description = "Description of light",
                        DateTime = DateTime.Now
                    });
            }
        }

        public IList<BulbItem> All()
        {
            return _connection.Table<BulbItem>()
                .ToList();
        }

        public BulbItem Latest
        {
            get
            {
                return _connection
                    .Table<BulbItem>()
                    .OrderByDescending(x => x.Id)
                    .FirstOrDefault();
            }
        }

        public BulbItem Get(int id)
        {
            return _connection.Get<BulbItem>(id);
        }

        public void Add(BulbItem bulbItem)
        {
            _connection.Insert(bulbItem);
        }

        public void Delete(BulbItem bulbItem)
        {
            _connection.Delete(bulbItem);
        }

        public void Update(BulbItem bulbItem)
        {
            bulbItem.DateTime = DateTime.Now;

            _connection.Update(bulbItem);
        }

        public List<BulbItem> Filter(string name)
        {
            return _connection.Table<BulbItem>()
                       .Where(item => item.Name == name)
                       .ToList();
        }

        public int Count()
        {
            return _connection.Table<BulbItem>().Count();
        }

        BulbItem IRepository<BulbItem>.Latest(Func<BulbItem, object> func)
        {
            return _connection
                .Table<BulbItem>()
                .OrderByDescending(func)
                .FirstOrDefault();
        }

        public List<BulbItem> Filter(Func<BulbItem, bool> func)
        {
            return _connection.Table<BulbItem>()
                       .Where(func)
                       .ToList();
        }

        public void Dispose()
        {
            //throw new NotImplementedException();
        }
    }
}
